<template>
  <x-drawer :visible.sync="skuVisible" title="填写订单" round cancel @cancel="closeSkuVisible">
    <scroll-view class="p-drawer" scroll-y>
      <view class="_header">
        <view class="_lf">
          <x-image :src="formatOss(thumbImg,300)" />
        </view>
        <view class="_rt">
          <view class="_price">
            <view style="display: flex;align-items: center">
              <x-price v-if="skuPrice" :price="skuPrice" :TipsSize="24" :Price1Size="couponInfo && skuCouponPrice ? 36 : 48" :Price2Size="36"></x-price>
              <view class="_coupon-price">
                <text class="_coupon-after">实付价<text style="margin: 0 4px">¥</text></text>
                <text>{{ orderInfo.totalPay || formatZero(skuCouponPrice) }}</text>
                <text v-if="!canBuy || !(addressInfo.addressInfo && addressInfo.addressInfo)" class="_up">起</text>
              </view>
            </view>
          </view>
          <view class="_text" v-if="selectArr && selectArr.length">
            已选：
            <text class="_tagselect" v-if="detail.productComboList && detail.productComboList.length > 0">
              {{detail.productComboList[comboIndex].comboName}}
            </text>
            <text class="_tagselect" v-for="(item, index) in selectArr" :key="index">
              <text v-if="item && item.length > 0">{{ getSelectArrItem(item) }}</text>
            </text>
          </view>
        </view>
      </view>
      <!-- 服务 -->
      <p-server :serveList="serveList" />

      <view class="_scroll">
        <!-- 规格展示 -->
        <div class="wrap wrap-sku">
          <div class="product-box">
            <div class="product-content">
              <div class="product-delcom" v-if="detail.skuMode === 3">
                <view class="spec-name">套餐</view>
                <ul class="product-footerlist clearfix" v-if="detail.productComboList && detail.productComboList.length > 0">
                  <li v-for="(item, index) in detail.productComboList" :class="[index === comboIndex ? 'productActive' : '']" :key="index" @click="checkCombo(index)">{{item.comboName}}</li>
                </ul>
                <view v-if="detail.productComboList[comboIndex].comboSellingPoint" class="spec-name comboSellingPoint">{{detail.productComboList[comboIndex].comboSellingPoint}}</view>
              </div>
              <div class="product-delcom" v-for="(ProductItem,n) in simulatedDATA.specInfo" :key="n">
                <view class="spec-name">{{ProductItem.specName}}</view>
                <ul class="product-footerlist clearfix">
                  <li
                    v-for="(oItem,index) in ProductItem.specValueList"
                    :key="index"
                    :class="[subIndex[n] === index ? 'productActive':'']"
                    @click="specificationBtn(oItem.specValue, n, ProductItem.specName, index)"
                  >
                    <text style="display: inline-block;margin: 0 auto">{{oItem.specValue}}</text>
                    <view class="tag-primary" v-if="oItem.recommendedFlag">
                      <x-icon name="icon-058" size="24" color="#ffffff" />
                      主推
                    </view>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>

        <view class="_num">
          <view class="_lf">数量</view>
          <view class="_rt">
            <view class="_jian">
              <x-button @click="reduce" :disabled="reduceDisabled" priority="secondary-secondary" size="medium" styles="border: none !important;background: #F2F3F5;padding: 0">
                <text style="font-size: 28px;line-height: 28px;">-</text>
              </x-button>
            </view>
            <view class="_num">
              <x-input placeholder=" " disabled :value="productCount" type="text" size="small" textAlign="center" background="#F2F3F5" />
            </view>
            <view class="_jian">
              <x-button @click="add" priority="secondary-secondary" size="medium" styles="border: none !important;background: #F2F3F5;padding: 0">
                <text style="font-size: 28px;line-height: 28px;">+</text>
              </x-button>
            </view>
          </view>
        </view>

        <view class="p-address">
          <view class="_title">
            <view class="_lf">收货地址</view>
            <!--#ifdef MP-WEIXIN-->
            <view class="_rt" @click="onAddress">
              <view class="_use-WeiXin">
                <x-icon style="margin-right: 4px;" name="icon-030" size="30" color="#07C160"/>
                使用微信收货地址
              </view>
              <x-icon name="icon-017" size="28" color="#999999"/>
            </view>
            <!--#endif-->
          </view>
          <view class="cell-group">
            <view class="cell">
              <view class="_lf-title">收货人</view>
              <view class="flex1 bold">
                <x-input size="mini" fontSize="30" maxlength="10" :value.sync="addressInfo.userName" placeholder="收货人姓名"/>
              </view>
            </view>
            <view class="cell">
              <view class="_lf-title">手机号</view>
              <view class="flex1 bold">
                <x-input size="mini" fontSize="30" maxlength="11" :value.sync="addressInfo.userPhone" type="number" placeholder="收货人手机号" @blur="handleBlurPhone" />
              </view>
            </view>
            <view class="cell">
              <view class="_lf-title">所在地区</view>
              <picker style="flex: 1" mode="region" :value="addressInfo.multiIndex" @change="multiChange">
                <view class="adress-info bold" :style="{'color' : addressInfo.addressInfo ? '#323233' : '#999999'}">
                  {{addressInfo.addressInfo || '省/市/区'}}
                </view>
              </picker>
              <view class="_rt">
                <x-icon name="icon-017" size="28" color="#999999"/>
              </view>
            </view>
            <view class="cell">
              <view class="_lf-title">详细地址</view>
              <view class="flex1 bold">
                <x-input size="mini" fontSize="30" maxlength="50" :value.sync="addressInfo.userAddress" placeholder="门牌号等（例如：10栋1001号）"/>
              </view>
            </view>
          </view>
        </view>

        <!--顺手购-->
        <p-conveniently v-if="detail.productType !== 5" :store-id="detail.storeId" :product-id="detail.id" @change="handleChangeConveniently" />

        <view class="order-compute">
          <view class="cell">
            <view class="_lf-title">商品数量</view>
            <view class="_rt">
              共
              <text class="_red">{{ productCountSum }}</text>
              件商品
            </view>
          </view>
          <view class="cell">
            <view class="_lf-title">商品总额</view>
            <view class="_rt">
              <text>
                <text class="font-24 margin-rt-6">¥</text>
                {{ productPriceSum }}
              </text>
            </view>
          </view>
          <view class="cell">
            <view class="_lf-title">运费</view>
            <view class="_rt _red">
              <text style="margin-right: 4px;">
                <text>{{addressInfo.userProvince ? (orderInfo.freightAmount === 0 ? '包邮' : '¥' + orderInfo.freightAmount) : '-'}}</text>
              </text>
            </view>
          </view>
          <view class="cell" v-if="orderInfo && couponList && couponList.length > 0" @click="choseCoupon">
            <view class="_lf-title">优惠券<text v-if="orderInfo.couponAmount" class="_red" style="margin-left: 6px;">(已推荐优惠)</text></view>
            <view class="_rt _red">
              <text v-if="orderInfo.couponAmount" style="margin-right: 4px;">-<text class="font-24 margin-rt-6">¥</text>{{ formatZero(couponInfo.couponAmount) }}</text>
            </view>
            <x-icon name="icon-017" size="20" color="#999999" style="margin-left: 10px"></x-icon>
          </view>
          <view class="cell" v-if="orderInfo && orderInfo.subsidyAmount">
            <text class="_lf-title">活动补贴</text>
            <text class="_rt _red">-{{ formatZero(orderInfo.subsidyAmount) }}</text>
          </view>
          <view class="cell">
            <view class="_lf-title"></view>
            <view class="_rt">
              <text>应付款：</text>
              <text class="_red" style="font-size: 20px;">
                <text class="font-26 margin-rt-6">¥</text>
                {{ payPrice }}
              </text>
            </view>
          </view>
          <view class="cell" style="border-top: 8px solid #F6F6F6;">
            <view class="_lf-title">买家留言</view>
            <view class="flex1">
              <x-input size="mini" :value.sync="addressInfo.userMessage" placeholder="选填：买家留言"/>
            </view>
          </view>
        </view>
      </view>
      <view class="_bottom">
        <!-- 固定购买 -->
        <view class="_bottom-fixed">
          <view class="_content">
            <p-fixed-discount :price="discountPriceSum" :gift="gift" />
            <view class="_btn">
              <x-button size="large" round="true" @click="buy">立即购买</x-button>
            </view>
            <!--隐私协议-->
            <p-privacy ref="ref-privacy" defaultChecked @onPrivacyBuy="buy" />
          </view>
        </view>
      </view>
    </scroll-view>
    <!-- 优惠券弹框 -->
    <p-drawer-check-coupon
      v-if="couponVisible"
      :visible.sync="couponVisible"
      :couponList="couponList"
      :productTotalPrice="orderInfo.productTotalPrice"
      :couponLimitAmount="orderInfo.couponLimitAmount"
      @change="useCheckCoupon"
      @close="getCouponList"
    />
    <x-pay-cancel v-if="payCancelVisible" :visible.sync="payCancelVisible" @confirm="onRequestPayment" @cancel="onCancelPay" />
  </x-drawer>
</template>

<script>
import { promisify, complete } from '@/utils/x-promisify';
import $sr from '@/utils/x-sr';
import CONFIG from '@/config';
import XDrawer from '@/components/x-drawer';
import XIcon from '@/components/x-icon';
import XImage from '@/components/x-image';
import XButton from '@/components/x-button';
import XInput from '@/components/x-input';
import XPrice from '@/components/x-price';
import PDrawerCheckCoupon from '@/pages/goods-detail/components/p-drawer-check-coupon';
import XPayCancel from '@/components/x-pay-cancel';
import PPrivacy from '@/pages/advertising/components/p-privacy';
import PConveniently from '@/pages/advertising/components/p-conveniently';
import PFixedDiscount from '@/pages/advertising/components/p-fixed-discount';
import PServer from '../p-server/index.vue';

import md5 from 'md5';
import RSA from 'wxmp-rsa';
import { mapState } from 'vuex';

export default {
  name: 'PDrawerSku',
  components: {
    PServer,
    XPrice,
    XDrawer,
    XIcon,
    XImage,
    XButton,
    XInput,
    XPayCancel,
    PDrawerCheckCoupon,
    PPrivacy,
    PConveniently,
    PFixedDiscount
  },
  props: {
    query: {
      type: Object,
      default: () => {}
    },
    visible: {
      type: Boolean,
      default: false
    },
    detail: {
      type: Object,
      default: () => {}
    },
    orderType: {
      type: String,
      default: '1'
    },
    groupMode: {
      type: String,
      default: '0'
    },
    groupNo: {
      type: String,
      default: ''
    },
    groupList: {
      type: Array,
      default: () => []
    },
    serveList: { // 服务信息
      type: Array,
      default: () => []
    },
    allCouponList: { // 店铺下所有券
      type: Array,
      default: () => []
    },
    gift: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      thumbImg: this.detail.productMainPic,
      skuVisible: this.visible,
      skuId: '',
      index: 0,
      reduceDisabled: false,
      productCount: 1,
      skuPrice: null,
      skuCouponPrice: null,
      couponVisible: false,
      couponList: [], // 可使用优惠券列表
      couponInfo: null, // 优惠券详情
      allCouponSend: null, // 领取全部优惠券
      listDetail: this.detail,
      canBuy: false, // 是否可以购买
      subIndex: [], //  是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
      selectArr: [], // 存放被选中的值
      comboIndex: 0, // 默认选中的套餐信息
      shopItemInfo: {}, // 存放要和选中的值进行匹配的数据
      // 模拟后台返回的数据 多规格
      simulatedDATA: {},
      orderInfo: {},
      addressInfo: {
        multiIndex: [],
        userName: '',
        userPhone: '',
        addressInfo: '',
        userProvince: '',
        userCity: '',
        userArea: ''
      },
      wxParams: {},
      payCancelVisible: false,
      // 交易组件支付，还是普通支付
      requestPayment: uni.requestPayment,
      incidentallyProduct: null,
      discountPriceSum: 0
    };
  },
  watch: {
    groupNo(val, oldVal) {
      this.groupNo = val;
    }
  },
  computed: {
    ...mapState({
      // 隐私勾选状态
      privacyChecked: state => state['pages'].privacyChecked
    }),
    checkCanSendCoupon() {
      const couponList = this.allCouponList;
      for (let j = 0; j < couponList.length; j++) {
        const coupon = couponList[j];
        if (coupon.usableStatus && coupon.couponStatus === 0) {
          return true;
        }
      }
      return false;
    },
    // 商品总数量
    productCountSum() {
      return this.incidentallyProduct ? this.productCount + 1 : this.productCount;
    },
    // 商品总金额
    productPriceSum() {
      let price = this.productCount * this.skuPrice;
      if (this.incidentallyProduct) {
        price += this.incidentallyProduct.additionalActivityPrice;
      }
      return this.$tools.formatZero(price);
    },
    // 应付金额
    payPrice() {
      let price = this.orderInfo.totalPay || this.skuCouponPrice;
      if (this.incidentallyProduct) {
        price += this.incidentallyProduct.additionalActivityPrice;
      }
      return this.$tools.formatZero(price);
    }
  },
  created() {
    this.initDetail();
  },
  methods: {
    async initDetail() {
      const _this = this;
      // 获取用户上次下单填写的收货地址信息
      await this.getAddressInfo();
      if (this.allCouponList) { // 如果该商品有优惠券可领取
        if (this.checkCanSendCoupon) {
          const params = {
            productId: this.detail.id,
            storeId: this.detail.storeId
          };
          this.$http({
            report: true,
            method: 'get',
            url: '/marketing/coupon/app/list/forall',
            data: params
          }).then((res) => {
            this.allCouponSend = res.data;
          }).catch(() => {

          });
        }
      }

      if (this.productCount <= 1) {
        this.reduceDisabled = true;
      }
      let totalSkuPrice = _this.skuPrice * _this.productCount;
      let discountPriceSum = 0;
      if (+this.orderType === 1) {
        // 单买
        this.skuPrice = this.detail.purchasePrice;
        this.couponInfo = this.checkCoupon();
        const coupon = _this.checkCoupon();
        if (this.detail.purchaseSubsidyAmount) {
          totalSkuPrice = totalSkuPrice - this.detail.purchaseSubsidyAmount;
          discountPriceSum += this.detail.purchaseSubsidyAmount;
        }
        if (coupon?.couponAmount) {
          _this.skuCouponPrice = _this.skuPrice - coupon.couponAmount > 0 ? _this.skuPrice - coupon.couponAmount : 0.01; // 券后价
          discountPriceSum += coupon.couponAmount;
        }
        this.discountPriceSum = discountPriceSum;
      } else {
        // 开团/参团
        this.skuPrice = this.detail.groupPrice;
        this.couponInfo = this.checkCoupon();
        const coupon = _this.checkCoupon();
        if (this.detail.groupSubsidyAmount) {
          totalSkuPrice = totalSkuPrice - this.detail.groupSubsidyAmount;
          discountPriceSum += this.detail.groupSubsidyAmount;
        }
        if (coupon?.couponAmount) {
          _this.skuCouponPrice = totalSkuPrice - coupon.couponAmount > 0 ? totalSkuPrice - coupon.couponAmount : 0.01; // 券后价
          discountPriceSum += coupon.couponAmount;
        }
        this.discountPriceSum = discountPriceSum;
      }
      _this.simulatedDATA.productSku = this.detail.productSku ? this.detail.productSku : [];
      // 无规格商品可直接下单
      if (this.detail.skuMode === 1) {
        this.couponInfo = this.checkCoupon();
        this.canBuy = true;
        this.getOrderInfo('noSku');
        return;
      }
      _this.simulatedDATA.productSku = this.detail.productSku ? this.detail.productSku : [];
      let skuSpecInfo = [];
      if (this.detail.skuMode !== 3) {
        skuSpecInfo = this.detail.productSku[0].skuSpec?.map((item) => ({
          specName: item.specName,
          specValueList: []
        }));
        this.detail.productSku.forEach((item) => {
          item.skuSpec.forEach((spec, index) => {
            if (skuSpecInfo[index].specValueList.findIndex((item) => item.specValue === spec.specValue) === -1) {
              skuSpecInfo[index].specValueList.push({
                specValue: spec.specValue,
                specPic: spec.specPic,
                recommendedFlag: spec.recommendedFlag === 1
              });
            }
          });
        });
        // 重新定义specInfo
        this.detail.specInfo = skuSpecInfo;
      } else {
        await this.checkCombo(this.comboIndex);
      }
      _this.simulatedDATA.specInfo = this.detail.specInfo;
      if (this.detail.skuMode !== 3) {
        // 如果不是套餐商品，执行默认sku选择操作
        await this.checkInitSku();
      }
    },
    getAddressInfo() {
      return new Promise((resolve, reject) => {
        uni.getStorage({
          key: 'user-address-info',
          success: async(res) => {
            this.addressInfo = res.data;
            await this.getCouponList();
            this.userCouponId = this.skuCouponInfo?.userCouponId;
            if (this.detail.skuMode === 1) {
              await this.getOrderInfo('first', true);
            }
            resolve(res);
          },
          fail: async(err) => {
            await this.getCouponList();
            this.userCouponId = this.skuCouponInfo?.userCouponId;
            resolve(err);
          }
        });
      });
    },
    async checkCombo(index) {
      this.comboIndex = index;
      const productComboList = this.detail.productComboList;
      let skuSpecInfo = [];
      skuSpecInfo = productComboList[index].productSku[0].skuSpec?.map((item) => ({
        specName: item.specName,
        specValueList: []
      }));
      productComboList[index].productSku.forEach((item) => {
        item.skuSpec.forEach((spec, index) => {
          if (skuSpecInfo[index].specValueList.findIndex((item) => item.specValue === spec.specValue) === -1) {
            skuSpecInfo[index].specValueList.push({
              specValue: spec.specValue,
              specPic: spec.specPic,
              recommendedFlag: spec.recommendedFlag === 1
            });
          }
        });
      });
      // console.log(index, this.comboIndex, skuSpecInfo, productComboList, 'checkCombo');
      this.simulatedDATA.productComboList = productComboList;
      this.simulatedDATA.productSku = productComboList[index].productSku;
      this.simulatedDATA.specInfo = skuSpecInfo;
      this.detail.specInfo = skuSpecInfo;
      // this.initShopItemInfo();
      // 页面重置
      this.subIndex = [];
      this.selectArr = [];
      this.checkItem();
      // 默认切换选中sku
      await this.checkInitSku();
    },
    initShopItemInfo() {
      const _this = this;
      // 初始化存储数据
      _this.shopItemInfo = {};
      if (this.detail.skuMode !== 3) {
        for (const i in _this.simulatedDATA.productSku) {
          const key = md5(_this.simulatedDATA.productSku[i].difference);
          _this.shopItemInfo[key] = _this.simulatedDATA.productSku[i]; // 修改数据结构格式，改成键值对的方式，以方便和选中之后的值进行匹配
        }
      } else {
        const index = this.comboIndex;
        const productComboList = this.detail.productComboList[index];
        for (const i in productComboList.productSku) {
          const key = md5(productComboList.productSku[i].difference);
          _this.shopItemInfo[key] = productComboList.productSku[i]; // 修改数据结构格式，改成键值对的方式，以方便和选中之后的值进行匹配
        }
      }
    },
    // 默认选中规格等处理
    async checkInitSku() {
      const _this = this;
      const specInfo = this.simulatedDATA.specInfo;
      //  上述代码替换为下
      this.initShopItemInfo();
      if (specInfo && specInfo.length > 0) {
        //  默认规格选择 0-不选择；1-选择第一个规格；2-选择价格最低
        if (this.detail.productSafeguard.defaultSku === 0) {
          // dosomething
          // 页面重置
          this.subIndex = [];
          this.selectArr = [];
          this.checkItem();
        } else {
          // 选择第一个规格
          const selectArr = [];
          for (let i = 0; i < specInfo.length; i++) {
            for (let j = 0; j < specInfo[i].specValueList.length; j++) {
              selectArr[i] = [specInfo[i].specName, specInfo[i].specValueList[0].specValue].join('@|@|@');
              this.subIndex.push(0); // 默认全部选中第一个规格
            }
          }
          this.selectArr = selectArr;
        }
      }
      _this.checkItem();
      // _this.$forceUpdate();
    },
    formatZero(val) {
      return this.$tools.formatZero(val);
    },
    // 格式化图片
    formatOss(url) {
      return this.$tools.formatOss(url);
    },
    //  关闭分享弹框
    closeSkuVisible() {
      this.skuVisible = false;
      this.$emit('update:visible', false);
    },
    // 数量加减
    add() {
      this.productCount = this.productCount + 1;
      if (this.productCount > 0) {
        this.reduceDisabled = false;
      }
      this.couponInfo = this.checkCoupon();
      // 判断可否使用/并使用最优优惠券
      this.getOrderInfo();
      console.log(this.couponInfo);
    },
    reduce() {
      this.productCount = this.productCount - 1;
      if (this.productCount <= 1) {
        this.reduceDisabled = true;
      }
      this.couponInfo = this.checkCoupon();
      // 判断可否使用/并使用最优优惠券
      this.getOrderInfo();
      console.log(this.couponInfo);
    },
    async getOrderInfo(type, hideToast) {
      if (!hideToast) {
        if (this.detail.skuMode !== 1) { // 有sku的商品下单
          if (!this.skuId) {
            uni.showToast({
              title: '请选择商品规格！',
              icon: 'none'
            });
            return;
          }
        }
      }

      const params = {
        pageId: this.pageId,
        productId: this.detail.id, // 商品ID
        skuId: this.skuId, // skuId
        productCount: this.productCount, // 商品数量
        orderType: this.orderType, // 订单类型：1-普通订单；2-开团；3-参团
        userCouponId: this.userCouponId || this.couponInfo?.userCouponId, // 优惠券ID
        userProvince: this.addressInfo?.userProvince, // 用户省份
        userCity: this.addressInfo?.userCity, // 用户城市
        userArea: this.addressInfo?.userArea, // 用户区域
        incidentallyProductId: this.incidentallyProduct?.productId, // 顺手购商品ID
        additionalActivityId: this.incidentallyProduct?.additionalActivityId // 顺手购活动ID
      };
      await this.$http({
        login: true,
        url: '/product/spu/order/info',
        method: 'post',
        data: params,
        report: true
      }).then(res => {
        const data = res.data || {};
        this.orderInfo = data;
        const { couponAmount, subsidyAmount } = data;
        let discountPriceSum = 0;
        discountPriceSum += (couponAmount || 0) + (subsidyAmount || 0);
        this.discountPriceSum = discountPriceSum;
      });
    },
    buy() {
      // 交易完成页查看订单按钮设置为显示
      this.$store.dispatch('pages/setData', {
        isShowOrderButton: true
      });
      const {
        source,
        sourcePageId,
        sourcePageType,
        associate,
        walkIndex,
        walkId,
        tx_cps_id
      } = this.query || {};
      if (!this.canBuy) {
        uni.showToast({
          title: '请选择商品规格！',
          icon: 'none'
        });
        return;
      }
      if (!this.addressInfo.userName.trim()) {
        uni.showToast({
          title: '请填写收货人姓名！',
          icon: 'none'
        });
        return false;
      }
      if (!/^1[3-9]\d{9}$/.test(this.addressInfo.userPhone)) {
        uni.showToast({
          title: '手机号格式输入不正确！',
          icon: 'none'
        });
        return;
      }
      if (!this.addressInfo.addressInfo || !this.addressInfo.userAddress) {
        uni.showToast({
          title: '请选择收货地址！',
          icon: 'none'
        });
        return;
      }
      uni.setStorage({
        key: 'user-address-info',
        data: this.addressInfo
      });
      // 校验隐私协议
      try {
        if (!this.privacyChecked) {
          this.$XTrack('privacy_checked', {
            checked: false
          });
          this.$refs['ref-privacy'].handleShowRemind();
          return false;
        }
      } catch (e) {
        console.warn('校验隐私协议出错了');
      }
      const pageUrlQuery = {
        productId: this.detail.id,
        skuPrice: this.skuPrice,
        productCount: this.productCount,
        orderType: this.orderType
      };
      if (this.detail.storeId) {
        pageUrlQuery.storeId = this.detail.storeId;
      }
      if (this.groupNo) {
        pageUrlQuery.groupNo = this.groupNo;
      }
      if (sourcePageId) {
        pageUrlQuery.sourcePageId = sourcePageId;
      }
      if (sourcePageType) {
        pageUrlQuery.sourcePageType = sourcePageType;
      }
      if (tx_cps_id) {
        pageUrlQuery.tx_cps_id = tx_cps_id;
      }
      if (source) {
        pageUrlQuery.source = source;
      }
      if (associate === 'COUPON_CODE') {
        // 卡包进入下单来源
        pageUrlQuery.source = 1008;
      }
      if (walkIndex) {
        pageUrlQuery.walkIndex = walkIndex;
        pageUrlQuery.walkId = walkId;
      }
      const params = {
        productId: this.detail.id, // 商品ID
        orderType: this.orderType, // 订单类型：1-普通订单；2-开团；3-参团
        userName: this.addressInfo.userName, // 收货人姓名
        userPhone: this.addressInfo.userPhone, // 收货人手机号
        userProvince: this.addressInfo.userProvince, // 省
        userCity: this.addressInfo.userCity, // 市
        userArea: this.addressInfo.userArea, // 区
        userAddress: this.addressInfo.userAddress, // 详细地址
        userMessage: this.addressInfo?.userMessage, // 用户留言
        productCount: this.productCount, // 购买数量
        orderSource: 1, // 订单来源：1-微信小程序；2-浏览器
        orderChannel: (this.scene === 1175 || this.scene === 1177) ? this.scene : 2, // 推广方式：1-腾讯广点通；2-99猫商城；3-智能超链；4-H5商城；
        userCouponId: this.userCouponId || this.couponInfo?.userCouponId, // 优惠券ID
        pageUrl: null, // 页面地址
        landingPageId: sourcePageId || '', // 落地页Id  通过聚合页下单传
        landingPageType: sourcePageType, // 落地页类型：1-基础图文落地页；2-沉浸式视频落地页
        orderScene: this.scene,
        // 顺手购买商品
        incidentallyProductId: this.incidentallyProduct?.productId,
        // 顺手购活动Id
        additionalActivityId: this.incidentallyProduct?.additionalActivityId
      };
      const {
        skuId,
        orderType,
        groupNo
      } = this;
      if (+orderType === 3) {
        // 参团订单，才传参团号
        params.groupNo = groupNo;
      }
      if (skuId) {
        params.skuId = skuId;
      }
      // 部分数据进行加密处理
      const rsa = new RSA();
      rsa.setPublicKey(CONFIG.publicKey);
      params.userName = rsa.encryptLong(params.userName);
      params.userPhone = rsa.encryptLong(params.userPhone);
      params.userAddress = rsa.encryptLong(params.userAddress);
      const _this = this;
      this.$http({
        login: true,
        url: '/order/order/asymmetric/save',
        method: 'post',
        data: params,
        report: true,
        alarm: true
      }).then(res => {
        // console.log(res);
        const wxParams = res.data;
        this.wxParams = wxParams;
        // 有数上报，下单
        this.srTrack('give_order');
        this.$XTrack('orderSuccessInfo', res.data);

        // 有数上报，支付
        this.srTrack('pay');
        this.requestPayment({
          orderInfo: wxParams.orderInfo,
          timeStamp: wxParams.timeStamp,
          paySign: wxParams.paySign,
          nonceStr: wxParams.nonceStr,
          signType: wxParams.signType,
          package: wxParams.package,
          success: () => {
            this.$XTrack('orderPaySuccess', _this.wxParams);
            this.srTrack('payed');
            // console.log(res);
            // console.log(_this);
            // console.log('orderType' + _this.query.orderType);
            this.$store.dispatch('message/requestSubscribeMessage', {
              subscribeNode: 1,
              subscribeType: 2,
              subscribeContent: _this.detail.id,
              storeId: _this.detail.storeId
            }).then(() => {
              // 这里需要判断开团，参团，普通订单类型
              uni.redirectTo({
                url: `/packages/order/pay-status/index?orderId=${wxParams.orderId}&orderType=${_this.orderType}&source=${_this.query?.source}&sourcePageId=${_this.query?.sourcePageId}&sourcePageType=${_this.query?.sourcePageType}`
              });
            }).catch(() => {
              // 这里需要判断开团，参团，普通订单类型
              uni.redirectTo({
                url: `/packages/order/pay-status/index?orderId=${wxParams.orderId}&orderType=${_this.orderType}&source=${_this.query?.source}&sourcePageId=${_this.query?.sourcePageId}&sourcePageType=${_this.query?.sourcePageType}`
              });
            });
          },
          fail: (err) => {
            console.log(err);
            this.clickStatus = true;
            try {
              if (err.errMsg.includes('cancel')) {
                this.payCancelVisible = true;
                this.$XTrack('cancelOrderPay', wxParams);
                // 有数上报，取消支付
                this.srTrack('cancel_pay');
              } else {
                this.$XTrack('errorOrderPay', err.errMsg);
              }
            } catch (e) {
              this.clickStatus = true;
            }
          }
        });
      }).catch(err => {
        console.log(err);
      });
    },
    specificationBtn(specValue, n, specName, index) {
      const specSku = [specName, specValue].join('@|@|@');
      const _this = this;
      if (_this.selectArr[n] !== specSku) {
        _this.selectArr[n] = specSku;
        _this.subIndex[n] = index;
        _this.checkItem();
      }
    },
    checkItem() {
      const _this = this;
      const option = _this.simulatedDATA.specInfo;
      const result = []; // 定义数组储存被选中的值
      for (const i in option) {
        result[i] = _this.selectArr[i] ? _this.selectArr[i] : '';
      }
      for (const i in option) {
        const last = result[i]; // 把选中的值存放到字符串last去
        for (const k in option[i].specValueList) {
          result[i] = [option[i].specName, option[i].specValueList[k].specValue].join('@|@|@'); // 赋值，存在直接覆盖，不存在往里面添加name值
        }
        result[i] = last; // 还原，目的是记录点下去那个值，避免下一次执行循环时被覆盖
      }
      // add
      for (const k in _this.shopItemInfo) {
        const info = _this.shopItemInfo[k];
        const difference = info.difference;
        const separate = info.separate;
        const skuLength = difference.split(separate).length;
        if (result.length === skuLength && result.indexOf('') === -1) {
          for (let i = 0; i < result.length; i++) {
            if (result.join(separate) === difference) {
              if (+_this.orderType === 1) { // 单买
                const subsidyRate = _this.detail.subsidyRate / 100 || 0;
                // _this.skuPrice = _this.shopItemInfo[k].skuPrice - (_this.shopItemInfo[k].skuPrice * subsidyRate) || ''; // 补贴价
                _this.skuPrice = _this.shopItemInfo[k].skuPrice || ''; // 补贴价现在只减一次
                const coupon = _this.checkCoupon();
                const totalSkuPrice = _this.skuPrice * _this.productCount - (_this.shopItemInfo[k].skuPrice * subsidyRate);
                if (coupon?.couponAmount) {
                  _this.skuCouponPrice = totalSkuPrice - coupon.couponAmount > 0 ? totalSkuPrice - coupon.couponAmount : 0.01; // 券后价
                } else {
                  _this.skuCouponPrice = totalSkuPrice;
                }
              } else { // 开团/参团
                const subsidyRate = _this.detail.subsidyRate / 100 || 0;
                // _this.skuPrice = _this.shopItemInfo[k].skuGroupPrice - (_this.shopItemInfo[k].skuGroupPrice * subsidyRate) || ''; // 补贴价
                _this.skuPrice = _this.shopItemInfo[k].skuGroupPrice || ''; // 补贴价现在只减一次
                const coupon = _this.checkCoupon();
                const totalSkuPrice = _this.skuPrice * _this.productCount - (_this.shopItemInfo[k].skuGroupPrice * subsidyRate);
                if (coupon?.couponAmount) {
                  _this.skuCouponPrice = totalSkuPrice - coupon.couponAmount > 0 ? totalSkuPrice - coupon.couponAmount : 0.01; // 券后价
                } else {
                  _this.skuCouponPrice = totalSkuPrice;
                }
              }
              _this.thumbImg = _this.shopItemInfo[k].thumbImg || this.detail.productMainPic;
              _this.skuId = _this.shopItemInfo[k].id;
              _this.canBuy = true;
            }
            // }
          }
        } else {
          // console.log('没有值');
          _this.skuId = '';
          _this.skuCouponPrice = _this.orderInfo.totalPay;
          _this.canBuy = false;
        }
      }
      // end
      if (!_this.canBuy) {
        // 判断可否使用/并使用最优优惠券
        _this.couponInfo = this.checkCoupon();
        console.log(_this.couponInfo, '可使用优惠券ID');
      }
      // 小庆说这个接口可以频繁调用，不用担心，用来计算没选择sku的最低价跟运费
      _this.getOrderInfo('getSku', true);
      _this.$forceUpdate(); // 重绘
    },
    // 判断可否使用/并使用最优优惠券
    checkCoupon() {
      const couponList = this.allCouponList || [];
      const canUse = [];
      const productPrice = this.$tools.formatNumber(this.skuPrice * this.productCount);
      for (let j = 0; j < couponList.length; j++) {
        // couponType 类型：1-满减券；2-直减券，usableStatus
        const coupon = couponList[j];
        if (coupon.usableStatus === 1 && (coupon.couponType === 2 || productPrice >= coupon.transactionAmount)) {
          canUse.push(couponList[j]);
        }
      }

      if (canUse.length > 0) {
        return canUse.sort((a, b) => {
          return b.couponAmount - a.couponAmount;
        })[0];
      } else {
        return null;
      }
    },
    // 领取优惠券并下单
    onCustomEvent(res) {
      // console.log(res);
      if (res.detail.errcode === 'OK') {
        // 通知服务端
        if (res.detail.send_coupon_result[0].coupon_code) {
          const allCoupon = [];
          for (let i = 0; i < res.detail.send_coupon_result.length; i++) {
            allCoupon.push({
              couponCode: res.detail.send_coupon_result[i].coupon_code,
              stockId: res.detail.send_coupon_result[i].stock_id
            });
          }
          const params = {
            couponList: allCoupon
          };
          this.$http({
            report: true,
            method: 'post',
            url: '/marketing/user/coupon/save/batch',
            data: params
          }).then((result) => {
            console.log(result);
            this.$XTrack('onCustomEvent');
            this.buy();
          }).catch(() => {
            this.buy();
          });
        } else {
          this.buy();
        }
      } else {
        this.buy();
      }
    },
    // 展示已选名称
    getSelectArrItem(item) {
      if (String(item).includes('@|@|@')) {
        return item.split('@|@|@')[1];
      } else {
        return item;
      }
    },
    // 输入完手机号之后获取是否有已经存在的地址信息
    handleBlurPhone(val) {
      if (/^1[3-9]\d{9}$/.test(val)) {
        this.$http({
          report: false,
          url: '/order/address/app/detail',
          data: {
            userPhone: val
          }
        }).then((res) => {
          if (res.data) {
            const { userAddress, userArea, userCity, userName, userProvince } = res.data;
            if (!this.addressInfo.userName) {
              this.addressInfo.userName = userName;
            }
            if (!this.addressInfo.userProvince) {
              Object.assign(this.addressInfo, {
                multiIndex: [userProvince, userCity, userArea],
                addressInfo: `${userProvince}-${userCity}-${userArea}`,
                userProvince: userProvince,
                userCity: userCity,
                userArea: userArea,
                userAddress: userAddress
              });
            }
          }
        });
      }
    },
    // 获取微信地址
    async onAddress() {
      await this.$store.dispatch('pages/setData', {
        clearStoreStorage: false
      });
      const scope = 'scope.address';
      const { authSetting } = await promisify(uni.getSetting)();
      console.info('uni.getSetting => ', authSetting);
      if (authSetting?.hasOwnProperty(scope)) {
        if (!authSetting[scope]) {
          await promisify(uni.openSetting)();
        }
      } else {
        await complete(uni.authorize)({ scope });
      }

      uni.chooseAddress({
        success: res => {
          this.addressInfo = {
            userName: res.userName,
            userPhone: res.telNumber,
            multiIndex: [res.provinceName, res.cityName, res.countyName],
            addressInfo: res.provinceName + '-' + res.cityName + '-' + res.countyName,
            userAddress: res.detailInfo,
            userProvince: res.provinceName,
            userCity: res.cityName,
            userArea: res.countyName
          };
          uni.setStorage({
            key: 'user-address-info',
            data: this.addressInfo
          });
          this.getOrderInfo('chooseAddress');
          this.$XTrack('chooseAddressEvent');
        },
        fail: () => {
        }
      });
    },
    // 区域选择
    multiChange(e) {
      const detail = e.detail.value;
      this.addressInfo.addressInfo = detail[0] + '-' + detail[1] + '-' + detail[2];
      this.addressInfo.multiIndex = e.detail.value;
      this.addressInfo.userProvince = detail[0];
      this.addressInfo.userCity = detail[1];
      this.addressInfo.userArea = detail[2];
      this.getOrderInfo('chooseAddress');
      this.$XTrack('inputRegionChangeEvent', e.detail.value); // 数据埋点，选择地址改变
    },
    // 使用优惠券弹框
    choseCoupon() {
      this.couponVisible = true;
    },
    // 选择优惠券
    useCheckCoupon(option) {
      console.log(option);
      this.couponInfo = option;
      // this.userCouponId = option.userCouponId;
      this.getOrderInfo();
      this.$XTrack('userCouponChangeEvent');
    },
    // 选择优惠券
    checkCouponSuccess(option) {
      console.log(option);
      this.userCouponId = option.userCouponId;
      this.getOrderInfo();
      this.$XTrack('userCouponChangeEvent');
    },
    // 获取可使用的优惠券列表
    async getCouponList() {
      const params = {
        storeId: this.detail.storeId,
        productId: this.detail.id
      };
      await this.$http({
        login: true,
        url: '/marketing/user/coupon/list/for/product',
        method: 'get',
        report: true,
        error: false,
        data: params
      }).then(res => {
        // console.log(res);
        this.couponList = res.data ? res.data : [];
        this.userCouponId = this.skuCouponInfo?.userCouponId;
      }).catch(() => {

      });
    },
    // 有数上报
    // give_order：用户提交订单；
    // pay：用户发起支付；
    // cancel_pay：用户关闭支付密码浮层；
    // payed：用户完成支付（影响有数实时订单统计）；
    // cancel_give_order：用户取消订单；
    // refund：用户发起退货退款
    srTrack(status) {
      const { totalPay, productPrice, productCount } = this.orderInfo;
      const { orderInfo } = this.wxParams;
      $sr.trackCustomOrder(status, {
        productPrice,
        totalPay,
        productCount,
        orderNo: orderInfo.out_order_id,
        createdAt: orderInfo.create_time
      });
    },
    onRequestPayment() {
      // 重新唤起支付
      // console.log('重新唤起支付');
      if (this.loading) return;
      const params = {
        orderId: this.wxParams.orderId,
        incidentallyOrderId: this.wxParams.incidentallyOrderId
      };
      this.loading = true;
      this.$http({
        login: true,
        url: '/order/order/repay',
        method: 'post',
        report: true,
        data: params
      }).then(res => {
        const wxParams = res.data;
        // 有数上报，支付
        this.srTrack('pay');
        this.requestPayment({
          orderInfo: wxParams.orderInfo,
          timeStamp: wxParams.timeStamp,
          paySign: wxParams.paySign,
          nonceStr: wxParams.nonceStr,
          signType: wxParams.signType,
          package: wxParams.package,
          success: (res) => {
            console.log(res);
            this.$XTrack('orderPaySuccess', Object.assign(wxParams, { isRepay: true }));
            uni.redirectTo({
              url: `/packages/order/pay-status/index?orderId=${wxParams.orderId}`
            });
          },
          fail: (err) => {
            console.log(err);
            if (err.errMsg.includes('cancel')) {
              this.payCancelVisible = true;
              this.$XTrack('cancelOrderPay', wxParams);
              // 有数上报，取消支付
              this.srTrack('cancel_pay');
            } else {
              uni.redirectTo({
                url: `/packages/order/detail/index?orderId=${wxParams.orderId}`,
                complete() {
                  setTimeout(() => {
                    uni.hideLoading();
                  }, 1000);
                }
              });
            }
          },
          complete: () => {
            this.loading = false;
          }
        });
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
      this.$XTrack('onRepayEvent');
    },
    onCancelPay() { // 重新唤起支付并且取消支付
      // console.log('重新唤起支付并且取消支付');
      const orderId = this.wxParams.orderId;
      uni.redirectTo({
        url: `/packages/order/detail/index?orderId=${orderId}`,
        complete() {
          setTimeout(() => {
            uni.hideLoading();
          }, 1000);
        }
      });
      this.$XTrack('cancelOrderPayEvent');
    },
    // 切换顺手购商品
    handleChangeConveniently(product) {
      this.$XTrack('changeConveniently', product);
      this.incidentallyProduct = product;
    }
  }
};
</script>

<style lang="scss" scoped>
.p-drawer{
  position: relative;
  background: #FFF;
  padding-bottom: env(safe-area-inset-bottom);
  width: 100%;
  max-height: 80vh;
  ._header{
    display: flex; position: sticky; top: 0; background-color: #fff; z-index: 9; padding: 24px 24px 10px;
    ._lf{
      width: 140px;
      height: 140px;
      border-radius: 6px;
      background: #FFECEC;
      margin-right: 22px;
    }
    ._rt{
      flex: 1;
      display: flex;
      flex-direction: column;
      ._price{
        display: flex;
        align-items: flex-start;
        flex: 1;
        width: 100%;
        font-size: 28px;
        color: $uni-color-primary;
        ._up {
          font-size: 26px;
          margin-left: 4px;
        }
        ._coupon-price{
          margin-left: 20px;
          margin-bottom: 4px;
          min-width: 184px;
          height: 46px;
          line-height: 46px;
          background: linear-gradient(270deg, #FF3A0F 0%, #FF7C32 100%);
          border-radius: 100px;
          text-align: center;
          color: #FFFFFF;
          font-size: 36px;
          padding: 0 18px;
          //margin-top: 8px;
          display: flex;
          align-items: center;
          ._coupon-after{
            font-size: 26px;
          }
        }
      }
      .align-baseline{
        display: flex;
        align-items: baseline;
      }
      ._text{
        width: 100%;
        font-size: 28px;
        color: $uni-color-secondary;
        -webkit-line-clamp: 1;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        ._tagselect{
          margin-left: 10px;
        }
      }
    }
  }
  ._service{
    font-size: 28px;
    color: $uni-color-default;
    display: flex;
    padding: 24px 24px 24px 24px;
    ._text{
      display: flex;
      color: #DBAE56;
      font-size: 28px;
      flex: 1;
      justify-content: flex-end;
      ._item{
        display: flex;
        align-items: center;
        margin-left: 16px;
        ._text{
          margin-left: 4px;
        }
      }
      ._item:first-child{
        margin-left: 0;
      }
    }
  }
  ._scroll{
    position: relative; padding-bottom: 30px;
    // add
    .wrap-sku {
      padding: 0 24px;
      .product-box {
        //width: 1200px;
        display: block;
        margin: 0 auto;
      }
      .product-content {
      }
      .product-delcom {
        color: #323232;
        font-size: 28px;
        display: flex;
        flex-direction: column;
        .spec-name{
          font-size: 30px;
          color: $uni-color-default;
        }
        .comboSellingPoint{
          margin-top: -10px;
          margin-bottom: 20px;
          color: #CE4031;
          font-size: 28px;
        }
      }
      .product-footerlist {
        padding-left: 0;
        margin-top: 30px;
      }
      .product-footerlist li {
        list-style: none;
        min-width: 144px;
        border-radius: 10px;
        color: $uni-color-default;
        text-align: center;
        padding: 18px 16px;
        float: left;
        font-size: 28px;
        line-height: 28px;
        margin-right: 30px;
        margin-bottom: 30px;
        background: $uni-bg-color-grey;
        border: 1px solid #F2F3F5;
        position: relative;
        .no-stock-productCount{
          position: absolute;
          width: 75px;
          height: 34px;
          line-height: 30px;
          background: #D9D9D9;
          border-radius: 6px;
          border: 2px solid #FFFFFF;
          font-size: 24px;
          color: #FFFFFF;
          padding: 0 6px;
          top: -20px;
          right: -16px;
        }
        .no-stock-productCount-active{
          background: #FFE2DF;
          color: #CE4031;
        }

        .tag-primary{
          position: absolute;
          top: -26px;
          right: -14px;
          display: flex;
          align-items: center;
          color: #FFFFFF;
          font-size: 24px;
          background: #EB431F;
          border-radius: 6px;
          padding: 6px 10px;
        }
      }
      .product-footerlist li.productActive {
        background-color: rgba(235, 68, 31, 0.06); color: #DE3A2E;border: 1px solid #DE3A2E;
      }
      .product-footerlist li.noneActive {
        //background: #F2F3F5;
        //color: #323233;
        //pointer-events: none;
      }
    }
    // end
    ._num{
      display: flex;
      padding: 16px 24px;
      align-items: center;
      border-bottom: 2px solid #eeeeee;
      ._lf{
        flex: 1;
        color: $uni-color-default;
        font-size: 28px;
        display: flex;
      }
      ._rt{
        display: flex;
        ._num{
          width: 76px;
          height: 64px;
          background: #F2F3F5;
          margin: 0 4px;
        }
        ._jian{
          width: 64px;
          height: 64px;
        }
      }
    }
  }
  ._bottom{
    box-shadow: 0px -4px 8px rgba(230, 177, 177, 0.2);padding-bottom: 1px;
    ._tips{
      text-align: center;
      font-size: 28px;
      color: $uni-color-info;
      padding: 16px;
      ._red{
        color: $uni-color-primary;
        margin: 0 4px;
      }
    }
    ._bottom-fixed{
      ._btn{
        width: 702px;
        margin: 16px 24px 32px 16px;
      }
    }
  }
  .p-address{
    margin-top: 16px;
    background: #FFFFFF;
    ._title{
      padding: 30px 24px;
      display: flex;
      border-bottom: 2px solid #eeeeee;
      ._lf{
        flex: 1;
        font-size: 30px;
        color: $uni-color-default;
      }
      ._rt{
        display: flex;
        align-items: center;
        font-size: 28px;
        color: $uni-color-success;
        ._use-WeiXin{
          margin-right: 4px;display: flex;align-items: center;
        }
      }
    }
    .cell-group{
      .cell{
        display: flex;
        align-items: center;
        padding: 0px 24px;
        height: 100px;
        border-bottom: 2px solid #eeeeee;
        ._lf-title{
          min-width: 112px;
          font-size: 30px;
          color: $uni-color-default;
          margin-right: 28px;
        }
        .adress-info{
          font-size: 30px;
        }
        .region-picker {
          overflow: hidden;
          width: 500px;
        }

        .region-item {
          &:last-child {
            margin-right: 0;
          }

          position: relative;
          width: 33%;
          line-height: 72px;
          padding-right: 30px;
          margin-right: 10px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;

          &:after {
            content: '';
            position: absolute;
            top: 30px;
            right: 6px;
            border: 14px solid #333;
            border-left: 6px solid transparent;
            border-bottom-color: transparent;
            border-right: 6px solid transparent;
          }
        }
      }
      .cell:last-child{
        border-bottom: none;
      }
    }
  }
  .order-compute{
    border-top: 16px solid #f6f6f6;
    background: #FFFFFF;
    .cell{
      display: flex;
      align-items: center;
      padding: 0 24px;
      height: 100px;
      border-bottom: 2px solid $uni-page-bg;
      ._lf-title{
        min-width: 112px;
        font-size: 30px;
        color: $uni-color-default;
        margin-right: 28px;
      }
      ._rt{
        flex: 1;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        font-size: 32px;
      }
    }
    .cell:last-child{
      border-bottom: none;
    }
  }
}

.bold{
  font-weight: 600;
}
</style>
